<?php
/**
 * Created by PhpStorm.
 * User: jjj
 * Date: 2017/9/18
 * Time: 14:59
 */

namespace app\common\model\exam;


use think\Cache;
use think\Db;
use think\Model;

/**
 * Class QuestionsClass
 * @package app\common\model\exam
 *
 * @property $class_parent
 */
class QuestionsClass extends Model
{
    protected $table = 'questions_class';
    protected $pk = 'class_id';

    /**
     * 获取树形分类
     *
     * @return mixed
     */
    public static function tree() {
        $sql = <<<SQL
SELECT * FROM questions_class WHERE class_parent=:parent
SQL;
        $list = Db::query($sql, ['parent' => 0]);
        foreach ($list as & $item) {
            $item['children'] = Db::query($sql, ['parent' => $item['class_id']]);
        }

        return $list;
    }


    const CLASS_TREE_KEY = 'class_tree';

    /**
     * @param bool $update_cache
     * @return mixed
     */
    public static function cacheTree($update_cache = false) {

        $c = Cache::tag('questions_class');
        $t = $c->get(self::CLASS_TREE_KEY);
        if ($update_cache || empty($t)) {
            $t = QuestionsClass::tree();
            $c->set(self::CLASS_TREE_KEY, $t);
        }

        return $t;
    }


}